package com.wy.redis;

import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.lang.Nullable;
import org.springframework.util.StringUtils;

import java.nio.charset.Charset;

public class StringPrefixRedisSerializer extends StringRedisSerializer {
    private String prefix;

    public StringPrefixRedisSerializer(Charset charset, String prefix) {
        super(charset);
        this.prefix = prefix;
    }

    public String deserialize(@Nullable byte[] bytes) {
        String tempKey = super.deserialize(bytes);
        if(!StringUtils.isEmpty(tempKey) && tempKey.startsWith(prefix) ){
            tempKey = tempKey.substring(prefix.length() + 1);
        }
        return tempKey;
    }

    public byte[] serialize(@Nullable String key) {

        return super.serialize(StringUtils.isEmpty(prefix) ? key : prefix + "." + key);
    }
}
